<?php 
session_start();

if (empty($_SESSION) || empty($_SESSION['authcode'])) {
	exit();
}
if (strlen($_SESSION['authcode']) != 5) {
	exit();
}
if (!isset($_POST['username']) || !isset($_POST['password']) || !isset($_POST['check'])) {
	exit();
}

require_once ('../conf/pdoConnect.php');

$password = md5($_POST['password']);
$username = trim($_POST['username']);
$code = trim($_POST['check']);
if ($code == "") {
	$code = "........";
}

$flag = false;
$err = "";

if (strlen($username) > 20) {
	$flag = true;
	$err = "用户名或密码错误";
	header("Location: ../login.php?error=$err");
	exit;
}

$trueCode = $_SESSION['authcode'];
unset($_SESSION['authcode']);		//销毁验证码，只能用一次

$ok = checkUser($db, $username, $password);

if ($code == $trueCode) {
	$flag = false;
	if ($ok) {
		$_SESSION['uid'] = $ok['id'];
		$_SESSION['user'] = $username;
		$_SESSION['ok'] = "yes";

		header("Location: ../main.php");
	} else {
		$flag = true;
		$err = "用户名或密码错误";
	}
} else {
	$flag = true;
	$err = "验证码错误";
}

if ($flag) {
	header("Location: ../login.php?error=$err");
	exit;
}
$db = null;

function checkUser($db, $un, $pwd) 
{
	$sql = "select * from user where `userName` = ? and `password` = ?";
	$stmt = $db->prepare($sql);
	$exec = $stmt->execute(array($un, $pwd));
	if ($exec) {
		$row = $stmt->fetch(PDO::FETCH_ASSOC);
	}
	return $row;
}




